package com.sddnytsh.body_buildingsystem.network

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 社区帖子API服务类
 * 处理与fitness-send的HTTP通信
 */
class CommunityApiService {
    
    private val client = OkHttpClient.Builder()
        .connectTimeout(5, TimeUnit.SECONDS)  // 连接超时：5秒
        .readTimeout(8, TimeUnit.SECONDS)     // 读取超时：8秒
        .writeTimeout(5, TimeUnit.SECONDS)    // 写入超时：5秒
        .retryOnConnectionFailure(true)       // 连接失败时重试
        .connectionPool(ConnectionPool(5, 5, TimeUnit.MINUTES)) // 连接池：5个连接，保持5分钟
        .build()
    
    /**
     * 执行网络请求的通用方法，包含重试机制
     */
    private suspend fun <T> executeRequestWithRetry(
        maxRetries: Int = 2,
        retryDelayMs: Long = 1000,
        request: suspend () -> Result<T>
    ): Result<T> = withContext(Dispatchers.IO) {
        var lastException: Exception? = null
        
        repeat(maxRetries + 1) { attempt ->
            try {
                val result = request()
                if (result.isSuccess) {
                    return@withContext result
                } else {
                    lastException = result.exceptionOrNull() as? Exception
                }
            } catch (e: Exception) {
                lastException = e
            }
            
            // 如果不是最后一次尝试，等待后重试
            if (attempt < maxRetries) {
                kotlinx.coroutines.delay(retryDelayMs * (attempt + 1)) // 递增延迟
            }
        }
        
        Result.failure(lastException ?: Exception("网络请求失败"))
    }
    
    private val gson = Gson()
    
    /**
     * 创建帖子
     */
    suspend fun createPost(post: CommunityPostCreateRequest): Result<CommunityPost> = withContext(Dispatchers.IO) {
        try {
            val requestBody = gson.toJson(post).toRequestBody("application/json".toMediaType())
            
            val request = Request.Builder()
                .url("${NetworkConfig.BASE_URL}/api/community-posts")
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    val data = apiResponse.data
                    // 后端返回的data直接包含帖子信息
                    val post = CommunityPost(
                        id = (data?.get("id") as? Number)?.toLong() ?: 0L,
                        userId = (data?.get("userId") as? Number)?.toLong() ?: 0L,
                        author = data?.get("author") as? String ?: "匿名用户",
                        title = data?.get("title") as? String ?: "",
                        content = data?.get("content") as? String ?: "",
                        likeCount = 0, // 新创建的帖子初始值为0
                        favoriteCount = 0,
                        commentCount = 0,
                        isLiked = false,
                        isFavorited = false,
                        createdAt = data?.get("createdAt") as? String ?: "",
                        updatedAt = data?.get("createdAt") as? String ?: ""
                    )
                    Result.success(post)
                } else {
                    Result.failure(Exception(apiResponse.message ?: "创建帖子失败"))
                }
            } else {
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 根据ID获取单个帖子详情
     */
    suspend fun getPostById(postId: Long, currentUserId: Long? = null): Result<CommunityPost> = withContext(Dispatchers.IO) {
        try {
            val url = if (currentUserId != null) {
                "${NetworkConfig.BASE_URL}/api/community-posts/$postId?currentUserId=$currentUserId"
            } else {
                "${NetworkConfig.BASE_URL}/api/community-posts/$postId"
            }
            
            val request = Request.Builder()
                .url(url)
                .get()
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    val data = apiResponse.data
                    // 单个帖子直接包含帖子信息
                    val post = CommunityPost(
                        id = (data?.get("id") as? Number)?.toLong() ?: 0L,
                        userId = (data?.get("userId") as? Number)?.toLong() ?: 0L,
                        author = data?.get("author") as? String ?: "匿名用户",
                        title = data?.get("title") as? String ?: "",
                        content = data?.get("content") as? String ?: "",
                        likeCount = (data?.get("likeCount") as? Number)?.toInt() ?: 0,
                        favoriteCount = (data?.get("favoriteCount") as? Number)?.toInt() ?: 0,
                        commentCount = (data?.get("commentCount") as? Number)?.toInt() ?: 0,
                        isLiked = data?.get("isLiked") as? Boolean ?: false,
                        isFavorited = data?.get("isFavorited") as? Boolean ?: false,
                        createdAt = data?.get("createdAt") as? String ?: "",
                        updatedAt = data?.get("updatedAt") as? String ?: ""
                    )
                    Result.success(post)
                } else {
                    Result.failure(Exception(apiResponse.message ?: "获取帖子详情失败"))
                }
            } else {
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 获取所有帖子
     */
    suspend fun getAllPosts(currentUserId: Long? = null): Result<List<CommunityPost>> = 
        executeRequestWithRetry {
            withContext(Dispatchers.IO) {
                try {
                    val url = if (currentUserId != null) {
                        "${NetworkConfig.BASE_URL}/api/community-posts?currentUserId=$currentUserId"
                    } else {
                        "${NetworkConfig.BASE_URL}/api/community-posts"
                    }
                    
                    val request = Request.Builder()
                        .url(url)
                        .get()
                        .addHeader("Content-Type", "application/json")
                        .build()
                    
                    val response = client.newCall(request).execute()
                    val responseBody = response.body?.string() ?: ""
                    
                    if (response.isSuccessful) {
                        val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                        val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                        
                        if (apiResponse.success) {
                            val data = apiResponse.data
                            // 直接从data中获取posts
                            val posts = data?.get("posts") as? List<*>
                            val postList = posts?.map { postData ->
                                val postMap = postData as Map<*, *>
                                CommunityPost(
                                    id = (postMap["id"] as? Number)?.toLong() ?: 0L,
                                    userId = (postMap["userId"] as? Number)?.toLong() ?: 0L,
                                    author = postMap["author"] as? String ?: "匿名用户",
                                    title = postMap["title"] as? String ?: "",
                                    content = postMap["content"] as? String ?: "",
                                    likeCount = (postMap["likeCount"] as? Number)?.toInt() ?: 0,
                                    favoriteCount = (postMap["favoriteCount"] as? Number)?.toInt() ?: 0,
                                    commentCount = (postMap["commentCount"] as? Number)?.toInt() ?: 0,
                                    isLiked = postMap["isLiked"] as? Boolean ?: false,
                                    isFavorited = postMap["isFavorited"] as? Boolean ?: false,
                                    createdAt = postMap["createdAt"] as? String ?: "",
                                    updatedAt = postMap["updatedAt"] as? String ?: ""
                                )
                            } ?: emptyList()
                            Result.success(postList)
                        } else {
                            Result.failure(Exception(apiResponse.message ?: "获取帖子失败"))
                        }
                    } else {
                        Result.failure(Exception("请求失败: ${response.code}"))
                    }
                } catch (e: Exception) {
                    Result.failure(e)
                }
            }
        }
    
    /**
     * 切换帖子点赞状态
     */
    suspend fun togglePostLike(userId: Long, postId: Long): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            val url = "${NetworkConfig.BASE_URL}/api/post-like/toggle?userId=$userId&postId=$postId"
            
            val request = Request.Builder()
                .url(url)
                .post("".toRequestBody("application/json".toMediaType()))
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    Result.failure(Exception(apiResponse.message ?: "点赞失败"))
                }
            } else {
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 切换帖子收藏状态
     */
    suspend fun togglePostFavorite(userId: Long, postId: Long): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            val url = "${NetworkConfig.BASE_URL}/api/post-favorite/toggle?userId=$userId&postId=$postId"
            
            val request = Request.Builder()
                .url(url)
                .post("".toRequestBody("application/json".toMediaType()))
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    Result.failure(Exception(apiResponse.message ?: "收藏失败"))
                }
            } else {
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 获取用户帖子列表
     */
    suspend fun getUserPosts(userId: Long, page: Int = 1, size: Int = 10): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "获取用户帖子列表请求: userId=$userId, page=$page, size=$size")
            val url = "${NetworkConfig.BASE_URL}/api/community-posts/user/$userId?page=$page&size=$size"
            
            val request = Request.Builder()
                .url(url)
                .get()
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "获取用户帖子列表响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    android.util.Log.d("CommunityApiService", "获取用户帖子列表成功: ${apiResponse.data}")
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    android.util.Log.e("CommunityApiService", "获取用户帖子列表失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "获取用户帖子列表失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "获取用户帖子列表请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "获取用户帖子列表异常", e)
            Result.failure(e)
        }
    }

    /**
     * 删除帖子
     */
    suspend fun deletePost(postId: Long, userId: Long): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "删除帖子请求: postId=$postId, userId=$userId")
            val url = "${NetworkConfig.BASE_URL}/api/community-posts/$postId?userId=$userId"
            
            val request = Request.Builder()
                .url(url)
                .delete()
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "删除帖子响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    android.util.Log.d("CommunityApiService", "删除帖子成功: ${apiResponse.data}")
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    android.util.Log.e("CommunityApiService", "删除帖子失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "删除帖子失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "删除帖子请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "删除帖子异常", e)
            Result.failure(e)
        }
    }

    /**
     * 获取用户评论列表
     */
    suspend fun getUserComments(userId: Long, page: Int = 1, size: Int = 20): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "获取用户评论列表请求: userId=$userId, page=$page, size=$size")
            val url = "${NetworkConfig.BASE_URL}/api/post-comments/user/$userId?page=$page&size=$size"
            
            val request = Request.Builder()
                .url(url)
                .get()
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "获取用户评论列表响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    android.util.Log.d("CommunityApiService", "获取用户评论列表成功: ${apiResponse.data}")
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    android.util.Log.e("CommunityApiService", "获取用户评论列表失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "获取用户评论列表失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "获取用户评论列表请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "获取用户评论列表异常", e)
            Result.failure(e)
        }
    }

    /**
     * 删除评论
     */
    suspend fun deleteComment(commentId: Long, userId: Long): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "删除评论请求: commentId=$commentId, userId=$userId")
            val url = "${NetworkConfig.BASE_URL}/api/post-comments/$commentId?userId=$userId"
            
            val request = Request.Builder()
                .url(url)
                .delete()
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "删除评论响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    android.util.Log.d("CommunityApiService", "删除评论成功: ${apiResponse.data}")
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    android.util.Log.e("CommunityApiService", "删除评论失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "删除评论失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "删除评论请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "删除评论异常", e)
            Result.failure(e)
        }
    }

    /**
     * 获取用户收藏列表
     */
    suspend fun getUserFavorites(userId: Long, page: Int = 1, size: Int = 20): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "获取用户收藏列表请求: userId=$userId, page=$page, size=$size")
            val url = "${NetworkConfig.BASE_URL}/api/post-favorite/user/$userId?page=$page&size=$size"
            
            val request = Request.Builder()
                .url(url)
                .get()
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "获取用户收藏列表响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    android.util.Log.d("CommunityApiService", "获取用户收藏列表成功: ${apiResponse.data}")
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    android.util.Log.e("CommunityApiService", "获取用户收藏列表失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "获取用户收藏列表失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "获取用户收藏列表请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "获取用户收藏列表异常", e)
            Result.failure(e)
        }
    }

    /**
     * 切换评论点赞状态
     */
    suspend fun toggleCommentLike(userId: Long, commentId: Long): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "评论点赞请求: userId=$userId, commentId=$commentId")
            val url = "${NetworkConfig.BASE_URL}/api/comment-like/toggle"
            
            val requestBody = mapOf(
                "userId" to userId,
                "commentId" to commentId
            )
            
            val request = Request.Builder()
                .url(url)
                .post(gson.toJson(requestBody).toRequestBody("application/json".toMediaType()))
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "评论点赞响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    android.util.Log.d("CommunityApiService", "评论点赞成功: ${apiResponse.data}")
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    android.util.Log.e("CommunityApiService", "评论点赞失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "评论点赞失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "评论点赞请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    /**
     * 获取评论的回复列表
     */
    suspend fun getReplies(commentId: Long, page: Int = 1, size: Int = 10): Result<Map<String, Any>> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "获取回复列表请求: commentId=$commentId, page=$page, size=$size")
            val url = "${NetworkConfig.BASE_URL}/api/post-comments/replies/$commentId?page=$page&size=$size"
            
            val request = Request.Builder()
                .url(url)
                .get()
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "获取回复列表响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    android.util.Log.d("CommunityApiService", "获取回复列表成功: ${apiResponse.data}")
                    Result.success(apiResponse.data ?: emptyMap())
                } else {
                    android.util.Log.e("CommunityApiService", "获取回复列表失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "获取回复列表失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "获取回复列表请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "获取回复列表异常", e)
            Result.failure(e)
        }
    }

    /**
     * 根据ID获取单个评论详情
     */
    suspend fun getCommentById(commentId: Long, currentUserId: Long? = null): Result<Comment> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "获取评论详情请求: commentId=$commentId, currentUserId=$currentUserId")
            val url = if (currentUserId != null) {
                "${NetworkConfig.BASE_URL}/api/post-comments/$commentId?currentUserId=$currentUserId"
            } else {
                "${NetworkConfig.BASE_URL}/api/post-comments/$commentId"
            }
            
            val request = Request.Builder()
                .url(url)
                .get()
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "获取评论详情响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    val data = apiResponse.data
                    val comment = Comment(
                        id = (data?.get("id") as? Number)?.toLong() ?: 0L,
                        postId = (data?.get("postId") as? Number)?.toLong() ?: 0L,
                        userId = (data?.get("userId") as? Number)?.toLong() ?: 0L,
                        content = data?.get("content") as? String ?: "",
                        likeCount = (data?.get("likeCount") as? Number)?.toInt() ?: 0,
                        isLiked = data?.get("isLiked") as? Boolean ?: false,
                        createdAt = data?.get("createdAt") as? String ?: "",
                        author = data?.get("author") as? String,
                        parentId = (data?.get("parentId") as? Number)?.toLong(),
                        rootId = (data?.get("rootId") as? Number)?.toLong(),
                        isDeleted = data?.get("isDeleted") as? Boolean ?: false
                    )
                    android.util.Log.d("CommunityApiService", "获取评论详情成功: $comment")
                    Result.success(comment)
                } else {
                    android.util.Log.e("CommunityApiService", "获取评论详情失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "获取评论详情失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "获取评论详情请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "获取评论详情异常", e)
            Result.failure(e)
        }
    }

    /**
     * 创建回复
     */
    suspend fun createReply(postId: Long, parentId: Long, rootId: Long, content: String): Result<Comment> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("CommunityApiService", "创建回复请求: postId=$postId, parentId=$parentId, rootId=$rootId, content=$content")
            val url = "${NetworkConfig.BASE_URL}/api/post-comments"
            
            val requestBody = mapOf(
                "postId" to postId,
                "userId" to UserState.currentUserId,
                "parentId" to parentId,
                "rootId" to rootId,
                "content" to content
            )
            
            val request = Request.Builder()
                .url(url)
                .post(gson.toJson(requestBody).toRequestBody("application/json".toMediaType()))
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string() ?: ""
            android.util.Log.d("CommunityApiService", "创建回复响应: code=${response.code}, body=$responseBody")
            
            if (response.isSuccessful) {
                val type = object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type
                val apiResponse = gson.fromJson<ApiResponse<Map<String, Any>>>(responseBody, type)
                
                if (apiResponse.success) {
                    val data = apiResponse.data
                    val comment = Comment(
                        id = (data?.get("id") as? Number)?.toLong() ?: 0L,
                        postId = (data?.get("postId") as? Number)?.toLong() ?: 0L,
                        userId = (data?.get("userId") as? Number)?.toLong() ?: 0L,
                        content = data?.get("content") as? String ?: "",
                        likeCount = (data?.get("likeCount") as? Number)?.toInt() ?: 0,
                        isLiked = data?.get("isLiked") as? Boolean ?: false,
                        createdAt = data?.get("createdAt") as? String ?: "",
                        author = data?.get("author") as? String,
                        parentId = (data?.get("parentId") as? Number)?.toLong(),
                        rootId = (data?.get("rootId") as? Number)?.toLong(),
                        isDeleted = data?.get("isDeleted") as? Boolean ?: false
                    )
                    android.util.Log.d("CommunityApiService", "创建回复成功: $comment")
                    Result.success(comment)
                } else {
                    android.util.Log.e("CommunityApiService", "创建回复失败: ${apiResponse.message}")
                    Result.failure(Exception(apiResponse.message ?: "创建回复失败"))
                }
            } else {
                android.util.Log.e("CommunityApiService", "创建回复请求失败: ${response.code}")
                Result.failure(Exception("请求失败: ${response.code}"))
            }
        } catch (e: Exception) {
            android.util.Log.e("CommunityApiService", "创建回复异常", e)
            Result.failure(e)
        }
    }
}
